<?php

//微信公用方法
//2017年5月23日 16:38:14
//author：silenceluo
//email:1095584081@qq.com

//获取随机字符串
function generateNonceStr($length=32)
{
	// 密码字符集，可任意添加你需要的字符
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
	$str ="";  
	for ( $i = 0; $i < $length; $i++ )  
	{  
		$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		//$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];  
	}  
	return $str;  
}

/**
 * 获取客户端ip地址
 * @return [type] [description]
 */
function get_client_ip_server() 
{
	return $_SERVER["REMOTE_ADDR"]; 
}

/**
 * xml编码
 * @param  [type] $data     [description]
 * @param  string $root     [description]
 * @param  string $item     [description]
 * @param  string $attr     [description]
 * @param  string $id       [description]
 * @param  string $encoding [description]
 * @return [type]           [description]
 */
function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') 
{
	if(is_array($attr))
	{
		$_attr = array();
		foreach ($attr as $key => $value) 
		{
		    $_attr[] = "{$key}=\"{$value}\"";
		}
		$attr = implode(' ', $_attr);
	}
	$attr   = trim($attr);
	$attr   = empty($attr) ? '' : " {$attr}";
	$xml   = "<{$root}{$attr}>";	
	$xml   .= data_to_xml($data, $item, $id);
	$xml   .= "</{$root}>";

	return $xml;
}

/**
 * xml编码
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function data_to_xml($data) 
{
	$xml = '';
	foreach ($data as $key => $val) 
	{
	    is_numeric($key) && $key = "item id=\"$key\"";
	    $xml    .=  "<$key>";
	    $xml    .=  ( is_array($val) || is_object($val)) ? data_to_xml($val)  : xmlSafeStr($val);
	    list($key, ) = explode(' ', $key);
	    $xml    .=  "</$key>";
	}

	return $xml;
}

function xmlSafeStr($str)
{   
	return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';   
}
